// 机构配置文件
// 从环境配置导入Organization类型
import { type Organization, getCurrentOrganizations } from './organizations.env';
// 从JSON文件导入机构数据
import organizationsData from './organizations.json';

// 重新导出Organization类型供其他文件使用
export type { Organization };

// 机构数据配置 - 优先使用环境配置，fallback到JSON文件
export const organizations: Organization[] = getCurrentOrganizations().length > 0 
  ? getCurrentOrganizations() 
  : organizationsData.organizations;

// 根据账号查找机构
export function findOrganizationByAccount(account: string): Organization | undefined {
  return organizations.find(org => org.account === account);
}

// 根据名称查找机构
export function findOrganizationByName(name: string): Organization | undefined {
  return organizations.find(org => org.name === name);
}

// 获取所有机构名称
export function getAllOrganizationNames(): string[] {
  return organizations.map(org => org.name);
}

// 获取所有机构账号
export function getAllOrganizationAccounts(): string[] {
  return organizations.map(org => org.account);
}

// 验证机构是否存在
export function validateOrganization(account: string, password: string): boolean {
  const org = findOrganizationByAccount(account);
  return org ? org.password === password : false;
}

// 添加新机构（运行时添加）
export function addOrganization(organization: Organization): void {
  const existingIndex = organizations.findIndex(org => org.account === organization.account);
  if (existingIndex >= 0) {
    organizations[existingIndex] = organization;
  } else {
    organizations.push(organization);
  }
}

// 删除机构
export function removeOrganization(account: string): boolean {
  const index = organizations.findIndex(org => org.account === account);
  if (index >= 0) {
    organizations.splice(index, 1);
    return true;
  }
  return false;
}

// 更新机构信息
export function updateOrganization(account: string, updates: Partial<Organization>): boolean {
  const org = findOrganizationByAccount(account);
  if (org) {
    Object.assign(org, updates);
    return true;
  }
  return false;
}